package com.group2.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import model.Goods;
import static model.netBase.IP;
import java.awt.*;
import model.*;
;
public class ShopShowFrame_User extends JFrame {
    private String currentName;
    private ArrayList<Goods> goods=new ArrayList<Goods>();
    private ArrayList<Goods> shopCar=new ArrayList<Goods>();
	public ShopShowFrame_User(String sId,Timer timer) throws SocketException {
        currentName=sId;
        init();
    }
    public void refreshMoney(JLabel money){
        try{
            Socket socket=new Socket(IP(),2000);
            socket.setSoTimeout(3000);
            //构建IO
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("61" + '\n'+currentName+'\n');
            bw.flush();
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            Object obj=ois.readObject();
            Account account=(Account) obj;
            money.setText(account.getAccountBalance()+"");
        }catch (Exception e){
            System.out.println("连接异常");
        }
    }
    public void init() throws SocketException {
    	
    	Font f = new Font("黑体", Font.PLAIN, 15);
    	Font g = new Font("黑体", Font.BOLD, 15);
    	Font d = new Font("黑体", Font.BOLD, 17);
    	this.setTitle("欢迎光临苏猫超市！");
    	this.setSize(530, 600);
    	this.setResizable(false);
        //jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    	//ImageIcon icon = new ImageIcon("/images/add.png");
        // 创建内容面板，使用边界布局
        JPanel panel = new JPanel();
        JPanel panel2=new JPanel(null);
        JPanel panel0 =new JPanel(null);
        JLabel intro=new JLabel("当前商店内全部商品信息如下：");
        JLabel instr=new JLabel("请输入您想要购买的商品：");

        JLabel monshow=new JLabel("一卡通余额：");
        JLabel money=new JLabel();
        refreshMoney(money);

        JTextField search=new JTextField("");
        
        intro.setFont(d);
        instr.setFont(f);
        JButton car= new JButton("我的购物车");
        car.setFocusPainted(false);
        JButton Search =new JButton();
        Search.setFocusPainted(false);
        Search.setIcon(new ImageIcon(UserLogOnFrame.class.getResource("/images/search.png")));
        JButton Add =new JButton();
        Add.setFocusPainted(false);
        Add.setIcon(new ImageIcon(UserLogOnFrame.class.getResource("/images/shopcar.png")));
       
       
        panel0.setBounds(0,0,450,100); 
        intro.setBounds(50,10, 300, 30);  
        instr.setBounds(50,50, 200, 30);
        search.setBounds(250,50,100,30);
        Search.setBounds(350,50,30,30);
        Add.setBounds(385,50,30,30);
        panel.setBounds(40,100,450,300);
        money.setBounds(150,410, 120, 40);
        money.setFont(g);
        monshow.setFont(g);
        monshow.setBounds(50,410, 120, 40);        
        panel2.setBounds(0,400, 550, 200);
        car.setFont(f);
        car.setBounds(180,460, 120, 40);

        JTable table = new JTable();
        // 表头（列名）
        Object[] columnNames = {"编号","图片","品名","种类","价格","剩余量"};
        try {
            Socket socket = new Socket(IP(), 2000);
            socket.setSoTimeout(3000);
            //构建IO
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("51" + '\n');
            bw.flush();
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            goods = (ArrayList<Goods>) ois.readObject();
            socket.close();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Object[][]rowData=new Object[goods.size()][6];
        for (int x = 0; x < goods.size(); x++) {
            rowData[x][0] = goods.get(x).getId();
            String image = goods.get(x).getPicAddress();
            ImageIcon icon = new ImageIcon((UserLogOnFrame.class.getResource(image)));
            rowData[x][1] = icon;
            rowData[x][2] = goods.get(x).getGoodsname();
            rowData[x][3] = goods.get(x).getGoodsstyle();
            rowData[x][4] = goods.get(x).getPrice();
            rowData[x][5] = goods.get(x).getSurplus();
        }

        // 创建 表格模型，指定 所有行数据 和 表头,数据不可改
        DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames) {
            public Class<?> getColumnClass(int columnIndex) {
                return getValueAt(0, columnIndex).getClass();
            }
        };
        table.setModel(tableModel);


        // 设置表格内容颜色
           table.setForeground(Color.BLACK);                   // 字体颜色
           table.setFont(new Font(null, Font.PLAIN, 14));      // 字体样式
           table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
           table.setSelectionBackground(Color.orange);     // 选中后字体背景
           table.setGridColor(Color.GRAY);                     // 网格颜色

           // 设置表头
           table.getTableHeader().setFont(f);  // 设置表头名称字体样式
           table.getTableHeader().setForeground(Color.blue);                // 设置表头名称字体颜色
           table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽
           table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

           // 设置行高
           table.setRowHeight(60);

           // 第一列列宽设置为40
           table.getColumnModel().getColumn(0).setPreferredWidth(60);

           // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
           table.setPreferredScrollableViewportSize(new Dimension(400, 280));

           // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
           JScrollPane scrollPane = new JScrollPane(table);
           // table.getColumnModel().ge;tColumn(5).setCellRenderer(new buttonadd("加购"));
           // 添加 滚动面板 到 内容面板
           panel.add(scrollPane);

           panel2.add(car);
           panel2.add(monshow);
           panel2.add(money);
           panel0.add(intro);
           panel0.add(instr);
           panel0.add(search);
           panel0.add(Search);
           panel0.add(Add);

           // 设置 内容面板 到 窗口
           this.getContentPane().add(panel0);
           this.getContentPane().add(panel);
           this.getContentPane().add(panel2);

            Search.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   if(search.getText().equals("")) {JOptionPane.showMessageDialog(null, "请输入内容！");}
                   else
                   {
                       try {
                           Socket socket=new Socket(IP(),2000);
                           socket.setSoTimeout(3000);
                           //构建IO
                           OutputStream os = socket.getOutputStream();
                           BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                           bw.write("52"+'\n'+search.getText()+'\n');
                           bw.flush();
                           InputStream is = socket.getInputStream();
                           ObjectInputStream ois = new ObjectInputStream(is);
                           Object obj = ois.readObject();
                           goods.clear();
                           goods=(ArrayList<Goods>) obj;
                           System.out.println(goods);
                           //构建表格
                           socket.close();
                       } catch (ClassNotFoundException ex) {
                           throw new RuntimeException(ex);
                       } catch (SocketException ex) {
                           throw new RuntimeException(ex);
                       } catch (UnknownHostException ex) {
                           throw new RuntimeException(ex);
                       } catch (IOException ex) {
                           throw new RuntimeException(ex);
                       }
                       if(goods.size()>0) {
                           Object[][]rowData1=new Object[50][6];
                           for (int y = 0; y < goods.size(); y++) {
                               rowData1[y][0] = goods.get(y).getId();
                               String image = goods.get(y).getPicAddress();
                               ImageIcon icon = new ImageIcon((UserLogOnFrame.class.getResource(image)));
                               rowData1[y][1] = icon;
                               rowData1[y][2] = goods.get(y).getGoodsname();
                               rowData1[y][3] = goods.get(y).getGoodsstyle();
                               rowData1[y][4] = goods.get(y).getPrice();
                               rowData1[y][5] = goods.get(y).getSurplus();
                           }
                           DefaultTableModel tableModel1 = new DefaultTableModel(rowData1, columnNames) {
                               public Class<?> getColumnClass(int columnIndex) {
                                   return getValueAt(0, columnIndex).getClass();
                               }
                           };
                           table.setModel(tableModel1);
                       }
                       else{
                           JOptionPane.showMessageDialog(null, "查无此商品！");
                       }
                   }
               }
           });
           Add.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int count=table.getSelectedRow();
                   String getSurplus=table.getValueAt(count,5).toString();
                   if(Integer.parseInt(getSurplus)>0){
                       JOptionPane.showMessageDialog(null, "添加商品成功！可前往购物车结算");
                       shopCar.add(goods.get(count));
                   }
                   else{
                       JOptionPane.showMessageDialog(null, "剩余量不足，请重新选择商品！");
                   }

               }
           });
           car.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   new ShoppingCar(currentName,shopCar).addWindowListener(new WindowAdapter() {
                       @Override
                       public void windowClosed(WindowEvent e) {
                           refreshMoney(money);
                       }
                   });
               }
           });

           //设置筛选条
           RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);
           table.setRowSorter(rowSorter);

           this.setLocationRelativeTo(null);
           this.setVisible(true);
    }
}
